import time

// `select` command
//   allows monitoring several channels at the same time without noticeable CPU load
//   consists of a list of possible transfers and associated branches of statements
//   similar to the `match` command

fn main() {
	ch := chan f64{cap: 1}
	ch2 := chan f64{cap: 1}
	ch3 := chan f64{}
	
	mut b := 0.0
	c := 1.0
	
	mut threads := []thread{}
	
	// setup go threads that will send on ch/ch2
	threads << go fn (the_channel chan f64) {
		time.sleep(500 * time.millisecond)
		the_channel <- 1.0
	}(ch)
	threads << go fn (the_channel chan f64) {
		time.sleep(100 * time.millisecond)
		the_channel <- 1.0
	}(ch2)
	threads << go fn (the_channel chan f64) {
		_ := <-the_channel		ch3 <- c {
			// do something if `c` was sent
			time.sleep(5 * time.millisecond)
			eprintln('> c: $c was send on channel ch3')
		}
	}(ch3)

	select {
		a := <-ch {
			// do something with `a`
			eprintln('> a: $a')
		}
		b = <-ch2 {
			// do something with predeclared variable `b`
			eprintln('> b: $b')
		}
		ch3 <- c {
			// do something if `c` was sent
			time.sleep(4000 * time.millisecond)
			eprintln('> c: $c was send on channel ch3')
		}
		5000 * time.millisecond {
			// do something if no channel has become ready within 0.5s
			eprintln('> more than 0.5s passed without a channel being ready')
		}
	}
	threads.wait()
	eprintln('> done')
}
